package com.candy.candysocket.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;

import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;

/**
 * @author suYanLong
 * @version 1.0
 * @date 2023/7/18 13:23
 * @Description 描述
 */
public class NettyClient {

    private final int port;

    private final String host;

    public NettyClient(int port, String host) {
        this.port = port;
        this.host = host;
    }

    public void start() throws InterruptedException {
        /*线程组*/
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            /*客户端启动必备*/
            b.group(group)/*把线程组传入*/
                    /*指定使用NIO进行网络传输*/
                    .channel(NioSocketChannel.class)
                    .remoteAddress(new InetSocketAddress(host, port))
                    .handler(new NettyClientHandler())
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new IdleStateHandler(0, 4, 0, TimeUnit.SECONDS));
                            socketChannel.pipeline().addLast(new StringEncoder());
                            socketChannel.pipeline().addLast(new HeartBeatClientHandler());
                        }
                    })
            ;
            /*连接到远程节点，阻塞直到连接完成*/
            ChannelFuture f = b.connect().sync();
            /*阻塞程序，直到Channel发生了关闭*/
            f.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully().sync();
        }
    }

//    public void connect(ChannelHandlerContext context) {
//        // 使用ScheduledExecutorService来延迟重连
//        ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
//        scheduler.schedule(() -> {
//            try {
//                // 尝试重新连接
//                b.connect(host, port).addListener((ChannelFutureListener) future -> {
//                    if (future.isSuccess()) {
//                        System.out.println("Reconnected successfully!");
//                    } else {
//                        System.err.println("Reconnection failed!");
//                        // 如果失败，可以再次尝试或记录错误
//                    }
//                });
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }, 10, TimeUnit.SECONDS);
//    }

    public static void main(String[] args) throws InterruptedException {
        new NettyClient(9999, "127.0.0.1").start();
    }

}
